//
//  OrderListViewController.m
//  ATMCash
//
//  Created by zhengchengfeng on 2024/9/9.
//

#import "OrderListViewController.h"
#import "OrderListTableViewCell.h"
#import "EmptyOrderTableCell.h"
#import "SelectAccountController.h"

#define kTabCell           @"kTabCell"
#define kTabNoDataCell     @"kTabNoDataCell"
#define kTabNoNetworkCell  @"kTabNoNetworkCell"

@interface OrderListViewController ()

@property (nonatomic) BOOL isOffsetY;

@property (nonatomic) BOOL isNoData,isNetworkError;

@property (nonatomic) NSInteger recorNoNetworkTimes;

@end

@implementation OrderListViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == 1 || status == 2){
            self.isNetworkError = NO;
            if (self.recorNoNetworkTimes == 1) {
                [self loadData];
            }
            self.recorNoNetworkTimes = 0;
        }
        else{
            self.isNetworkError = YES;
            self.recorNoNetworkTimes = 1;
            [self.data removeAllObjects];
            DLog(@"============AFNetworkReachabilityStatusNotReachable========");
        }
       
        [self.tableView reloadData];
    }];
    
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    [self loadData];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = self.tableView.backgroundColor = RGB(4, 44, 8);
    self.tableView.frame =  CGRectMake(0, 0, kScreenWidth, kScreenHeight - 50);
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kGeneralHeight)];
    
    [self.tableView registerClass:[EmptyOrderTableCell class] forCellReuseIdentifier:kTabNoDataCell];
    [self.tableView registerClass:[EmptyOrderTableCell class] forCellReuseIdentifier:kTabNoNetworkCell];
    [self.tableView registerClass:[OrderListTableViewCell class] forCellReuseIdentifier:kTabCell];
    
}

- (void)loadData{
    
    if (![[CurrentUser mine] hasLogged] || self.isNetworkError) {
        [CreaditUtilsHelper hideLoadMessageBoxFromView:self.view];
        [CreaditUtilsHelper hideLoadMessageBox];
        return;
    }
    
    NSString *str = @"";
    if (self.categoryIndex == 0) {
        str = @"4";
    }
    else if (self.categoryIndex == 1) {
        str = @"7";
    }
    else if (self.categoryIndex == 2) {
        str = @"6";
    }
    else if (self.categoryIndex == 3) {
        str = @"5";
    }
    NSMutableDictionary *muDic = @{
        @"pastures":esString(str),
    }.mutableCopy;
    
    [CreaditUtilsHelper boxShowLoadWithMessage:@"" onView:self.view withOffsetHeight:-285];
    
    [BaseDataEngine apiForPath:kOrderListUrl method:kPostMethod parameter:muDic onCompleteSuccess:^(NSDictionary *responseDic) {
        DLog(@"-----%@",responseDic);
        [CreaditUtilsHelper hideLoadMessageBoxFromView:self.view];
        [CreaditUtilsHelper hideLoadMessageBox];
        if ([responseDic[@"dim"] integerValue] != kSuccessCode) {
            [CreaditUtilsHelper boxShowErrorWithMessage:esString(responseDic[@"platform"]) duration:2.5f];
            return;
        }
        [self.data removeAllObjects];
        
        NSDictionary *dic = responseDic[@"recollecting"];
        
        NSArray *pinAry = dic[@"vanity"];
       
        
        self.data = [OrderModel mj_objectArrayWithKeyValuesArray:pinAry];
        
        if (self.data.count == 0) {
            self.isNoData = YES;
        } else {
            self.isNoData = NO;
        }
        
        [self.tableView reloadData];
        
    } onCompleteFailur:^(NSError *error) {
        [CreaditUtilsHelper hideLoadMessageBoxFromView:self.view];
        [CreaditUtilsHelper hideLoadMessageBox];
    } withIsForm:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (self.isNoData) {
        return 1;
    }
    else if (self.isNetworkError) {
        return 1;
    }
    return self.data.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UIImage *img = [UIImage imageNamed:@"icon_empty"];
    UIImage *btnImg = [UIImage imageNamed:@"icon_emptyBtn"];
    if (self.isNoData) {
        return 40 + img.size.height + 5 + 5 + btnImg.size.height + 20 + 40;
    }
    else if (self.isNetworkError) {
        return 20 + img.size.height + 5 + 5 + btnImg.size.height + 20 + 60;
    }
    return [OrderListTableViewCell getCellHeight:self.data[indexPath.section]];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.isNoData) {
        EmptyOrderTableCell *cell = [tableView dequeueReusableCellWithIdentifier:kTabNoDataCell];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.isNoData = YES;
        cell.clickBtnBlock = ^{
            [self goApply];
        };
        return cell;
    }
    else if (self.isNetworkError) {
        EmptyOrderTableCell *cell = [tableView dequeueReusableCellWithIdentifier:kTabNoNetworkCell];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.isNoData = NO;
        cell.clickBtnBlock = ^{
            TipsAlertView *alertV = [[TipsAlertView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withTitleStr:@"To use Mabilis Money,you must enable network permission to use the App functions normally." withCancelStr:@"Stop" withSureStr:@"Turning On"];
            
            UIWindow *window =  [UIApplication sharedApplication].keyWindow;
            if (@available(iOS 14,*)) {
                window =  [[[UIApplication sharedApplication] windows] objectAtIndex:0];
            }
            [window addSubview:alertV];
            
            alertV.clickSureBlock = ^{
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:^(BOOL success) {
                                    
                }];
            };
        };
        return cell;
    }
    OrderListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTabCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.data[indexPath.section];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.isNetworkError || self.data.count == 0) {
        return;
    }
    
    OrderModel *model = self.data[indexPath.section];
    DLog(@"====%@",esString(model.rejoining.ahead));
    
    [[CreditCore globleCore] jumpToPage:esString(model.rejoining.ahead)];
    
}

- (void)goApply{
    [self.tabBarController setSelectedIndex:0];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"Sss" object:nil userInfo:@{@"index":@"1"}];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footV = [[UIView alloc] init];
    return footV;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 15;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *secV = [[UIView alloc] init];
    return secV;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0001f;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (self.isNetworkError) {
        return;
    } 
//    if (self.isNoData || self.isNetworkError) {
//        return;
//    }
    
    CGFloat offset_Y = scrollView.contentOffset.y;
   
    
    if (offset_Y < 0) {
        if (offset_Y < - kNavigationBarHeight) {
            self.isOffsetY = YES;
        }
        
    }else{
        
        if (self.isOffsetY) {
            self.isOffsetY = NO;
//            [CreaditUtilsHelper boxShowLoadWithMessage:@"" onView:self.view withOffsetHeight:-285];
            [self loadData];
        }
        
    }
}

@end
